<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { Input, Select, SelectOption, Tag } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import Icon from '#/components/Icons';

const optionsArr = new Set(['checkbox', 'radio', 'select']);

const inputRef = ref();
const state: any = reactive({
  attribute: {
    options: [],
  },
  group_type: 'parameter',
  group_index: -1,
  attribute_index: -1,
  inputVisible: false,
  inputValue: '',
  typeOptions: [
    { label: '输入框', value: 'text' },
    { label: '文本域', value: 'textarea' },
    { label: '富文本 ', value: 'html' },
    { label: '单选框', value: 'radio' },
    { label: '多选框', value: 'checkbox' },
    { label: '选择器', value: 'select' },
    { label: '计数器', value: 'number' },
    { label: '单图片', value: 'image' },
    { label: '多图片', value: 'images' },
    { label: '单附件', value: 'file' },
    { label: '多附件', value: 'files' },
    { label: '开关', value: 'switch' },
    { label: '位置', value: 'location' },
    { label: '颜色选择器', value: 'color' },
    { label: '时间选择器', value: 'time' },
    { label: '日期选择器', value: 'date' },
    { label: '日期时间选择器', value: 'datetime' },
  ],
});

const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
    labelClass: 'w-2/6',
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      dependencies: {
        show: false,
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'id',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'name',
      label: '名称',
      rules: 'required',
    },
    {
      component: 'Select',
      defaultValue: '',
      dependencies: {
        disabled: true,
        triggerFields: ['type'],
      },
      fieldName: 'type',
      label: '类型',
      rules: 'required',
    },
    {
      component: 'Select',
      fieldName: 'options',
      componentProps: {
        class: 'flex-wrap',
      },
      dependencies: {
        show(values) {
          return optionsArr.has(values.type);
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['type', 'options'],
      },
      defaultValue: [],
      label: '选项',
    },
    {
      component: 'Switch',
      defaultValue: 1,
      componentProps: {
        class: '',
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '停用',
      },
      fieldName: 'status',
      label: '状态',
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'value',
      label: '默认值',
    },
  ],
});

const [AttributesFormModal, AttributesFormModalApi] = useVbenModal({
  fullscreenButton: false,
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen) {
    if (!isOpen) return;
    const modalData = AttributesFormModalApi.getData();
    state.attribute = modalData?.attribute ?? { options: [] };
    state.group_index = modalData.group_index;
    state.group_type = modalData.group_type;
    state.attribute_index = modalData.attribute_index;
    const type = modalData.group_type === 'spec' ? 'select' : 'text';
    state.attribute.type = type;
    formApi.setValues(state.attribute);
  },
});

const handleClose = (removedTag: string) => {
  const tags = state.attribute.options.filter((tag: any) => tag !== removedTag);
  state.attribute.options = tags;
};

const showInput = () => {
  state.inputVisible = true;
  nextTick(() => {
    inputRef.value.focus();
  });
};

const handleInputConfirm = () => {
  const inputValue = state.inputValue;
  let tags = state.attribute.options || [];
  if (inputValue && !tags.includes(inputValue)) {
    tags = [...tags, inputValue];
  }
  Object.assign(state, {
    attribute: { options: tags },
    inputVisible: false,
    inputValue: '',
  });
  formApi.setValues(state.attribute);
};

async function onSubmit(values: any) {
  values.options = optionsArr.has(values.type) ? state.attribute.options : '';
  AttributesFormModalApi.setData({
    values: {
      group_index: state.group_index,
      attribute_index: state.attribute_index,
      attribute: cloneDeep(values),
    },
    isUpdata: true,
  });
  AttributesFormModalApi.close();
}
</script>
<template>
  <AttributesFormModal>
    <Form>
      <template #type="slotProps">
        <Select v-bind="slotProps" placeholder="请选择" style="width: 100%">
          <SelectOption
            v-for="item in state.typeOptions"
            :key="item.value"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; font-size: 13px; color: #8492a6">
              {{ item.value }}
            </span>
          </SelectOption>
        </Select>
      </template>
      <template #options>
        <div class="flex flex-wrap items-start">
          <template v-for="tag in state.attribute.options" :key="tag">
            <Tag class="mb-4" closable @close="handleClose(tag)">
              {{ tag }}
            </Tag>
          </template>
          <Input
            v-if="state.inputVisible"
            ref="inputRef"
            v-model:value="state.inputValue"
            :style="{ width: '78px' }"
            size="small"
            type="text"
            @blur="handleInputConfirm"
            @keyup.enter="handleInputConfirm"
          />
          <Tag
            v-else
            style="padding: 6px; background: #fff; border-style: dashed"
            @click="showInput"
          >
            <Icon icon="ri:add-line" />
          </Tag>
        </div>
      </template>

      <template #value="slotProps">
        <template v-if="state.group_type === 'spec'">
          <Select v-bind="slotProps" placeholder="请选择" style="width: 100%">
            <SelectOption
              v-for="(item, key) in state.attribute.options"
              :key="key"
              :value="item"
            />
          </Select>
        </template>
        <template v-else>
          <Input v-bind="slotProps" type="text" />
        </template>
      </template>
    </Form>
  </AttributesFormModal>
</template>

<style lang="scss" scoped></style>
